using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using UnityEngine;

public class GameSetting: MonoSingleton<GameSetting>
{
    private const string SETTING_DATA_FILE_NAME = "game_setting.json";
    public SettingData settingData = new SettingData();
    private bool isDirty = false;
    protected override void AutoInit()
    {
        var path = Path.Combine(Application.persistentDataPath, SETTING_DATA_FILE_NAME);
        if (File.Exists(path))
        {
            var jsonStr = File.ReadAllText(path);
            settingData = JsonConvert.DeserializeObject<SettingData>(jsonStr);
        }
    }

    public void Save(bool isImmediate = false)
    {
        if (isImmediate)
        {
            var jsonStr = JsonConvert.SerializeObject(settingData, new JsonSerializerSettings {ContractResolver = new FieldOnlyResolver()});
            var path = Path.Combine(Application.persistentDataPath, SETTING_DATA_FILE_NAME);
            File.WriteAllText(path, jsonStr);
            isDirty = false;
        }
        else{
            isDirty = true;
        }
    }

    void Update()
    {
        if (isDirty)
        {
            Save(true);
        }
    }
}


[Serializable]
public class SettingData
{
    public Dictionary<string, Vector3> uiPosMap = new Dictionary<string, Vector3>();
    public float speed = 1.0f;
    public float size = 1.0f;
    public bool neverSleep = true;
    public bool showFloatKeys = true;
    public CV cv = CV.Hachiware;
    public float alpha = 0.7f;
}

public class FieldOnlyResolver : DefaultContractResolver
{
    protected override List<MemberInfo> GetSerializableMembers(Type objectType)
    {
        // 只选择字段（包括私有字段）
        return objectType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
                        .Cast<MemberInfo>()
                        .ToList();
    }
}